import json
import re

from django.contrib.auth import authenticate, login, logout

from django.http import JsonResponse
from django.shortcuts import render
from django.views import View

# Create your views here.

# 接收注册信息
from django.views import View

# post登陆
from apps.user.models import User, Collection_job


class LoginView(View):
    # post 接收数据
    def post(self, request):
        # username  用户名
        # password  密码
        # rememberMe 是否记住

        data = request.body
        data_dict = json.loads(data)

        print(data_dict)
        username = data_dict.get("username")
        password = data_dict.get("password")
        rememberMe = data_dict.get("rememberMe")

        print(username, password)
        if not all([username, password]):
            return JsonResponse({"code": 401, "errmsg": "参数不全"})
        # 判断是否记住登陆
        if rememberMe:
            request.session.set_expiry(None)

        else:
            request.session.set_expiry(0)

            # 根据用户传入的username值，判断手机号还是用户名
        if re.match('1[3-9]\d{9}', username):
            User.USERNAME_FIELD = "mobile"

        else:
            User.USERNAME_FIELD = "username"
            # 验证用户名和密码是否正确
            user = authenticate(username=username, password=password)

            if user is None:
                return JsonResponse({"code": "400", "errmsg": "用户名或者密码错误"})
            # 保持登录状态
            login(request, user)

            response = JsonResponse({"code": "0", "errmsg": "ok"})
            # 把用户名保存到cookie 方便在首页显示 有效期产品决定
            # print("-------",user.username)
            response.set_cookie('username', user.username, max_age=3600 * 24 * 5)

            # 6 返回响应
            return response


# 显示注册页面
class Register(View):
    def get(self, request):
        return render(request, 'register.html')


# 接收注册信息
class RegisterView(View):
    def post(self, request):
        data = request.body
        data_dict = json.loads(data)

        print(data_dict)
        username = data_dict.get("username")
        password = data_dict.get("password")
        phone = data_dict.get("phone")
        #
        # print(username, password, phone)
        # 判断数据是否存在
        if not all([username, password, phone]):
            return JsonResponse({"code": 400, "errmsg": "缺少参数"})

        # 数据库保存
        try:
            count = User.objects.count()
            print('-------', count)
            if count == 0:
                user = User.objects.create_user(username=username, password=password, phone=phone, is_admin=1)
            # if user is None:
            else:
                user = User.objects.create_user(username=username, password=password, phone=phone)
            # 密码加密   数据保存可能不成功捕获异常
        except Exception as e:
            print(e)

            return JsonResponse({'code': 400, 'errmsg': "用户名或手机号已存在"})

        login(request, user)

        # 第一个注册的用户为管理员

        response = JsonResponse({"code": 0, "errmsg": "ok"})
        # 把用户名保存到cookie 方便在首页显示 有效期产品决定
        # response.set_cookie('username', user.username, max_age=3600 * 24 * 5)

        # 5返回响应（json数据）
        return response


# 修改密码
class PasswordUpdate(View):
    def post(self, request):

        data = request.body
        data_dict = json.loads(data)

        print(data_dict)

        old_password = data_dict.get("old_password")
        new_password = data_dict.get("new_password")
        new_password2 = data_dict.get("new_password2")

        if not all([old_password, new_password, new_password2]):
            return JsonResponse({"code": 400, "errmsg": "缺少参数"})

        if new_password != new_password2:
            return JsonResponse({'code': 400, 'errmsg': '两次密码不一样!'})

        # 从数据库修改密码
        try:
            request.user.set_password(new_password)
            request.user.save()
            print("修改成功")
        except Exception as e:
            print("修改密码失败", e)

        logout(request)
        response = JsonResponse({"code": "0", "errmsg": "ok"})
        # response = render(request, 'admin/login.html')

        # 4.删除cookie
        response.delete_cookie('username')

        return response


class LoginOut(View):
    def delete(self, request):
        logout(request)

        response = JsonResponse({"code": "0", "errmsg": "ok"})

        response.delete_cookie('username')

        return response


class AddUserInfo(View):
    def post(self, request):
        data = request.body
        data_dict = json.loads(data)
        username = data_dict.get('username')
        phone = data_dict.get('phone')
        is_admin = data_dict.get('is_admin')
        # job_monthly_pay = data_dict.get('job_monthly_pay')
        # job_education = data_dict.get('job_education')
        # job_address = data_dict.get('job_address')
        # job_count = data_dict.get('job_count')
        # job_major = data_dict.get('job_major')
        # create_time = data_dict.get('create_time')

        if not all([username, phone]):
            return JsonResponse({"code": 400, "errmsg": "缺少参数"})

        try:
            job = User.objects.create(username=username, phone=phone)
            # 密码加密   数据保存可能不成功捕获异常
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, 'errmsg': "就业信息保存失败"})

        response = JsonResponse({"code": 0, "errmsg": "ok"})
        return response


class ChangeUserInfo(View):
    def post(self, request, id):
        data = request.body
        data_dict = json.loads(data)
        username = data_dict.get('username')
        phone = data_dict.get('phone')
        is_admin = data_dict.get('is_admin')
        # job_monthly_pay = data_dict.get('job_monthly_pay')
        # job_education = data_dict.get('job_education')
        # job_address = data_dict.get('job_address')
        # job_count = data_dict.get('job_count')
        # job_major = data_dict.get('job_major')
        # create_time = data_dict.get('create_time')

        if not all([username, phone]):
            return JsonResponse({"code": 400, "errmsg": "缺少参数"})

        try:
            job = User.objects.filter(id=id).update(username=username, phone=phone)
            # 密码加密   数据保存可能不成功捕获异常
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, 'errmsg': "用户信息修改失败"})

        response = JsonResponse({"code": 0, "errmsg": "ok"})
        return response


class DeleteUserInfo(View):
    def post(self, request, id):

        try:

            user = User.objects.get(id=id)
            user.delete()

        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, 'errmsg': "就业信息删除失败"})

        response = JsonResponse({"code": 0, "errmsg": "ok"})
        return response


class CollectionInfo(View):
    def post(self, request):
        user_id = request.user.id
        data = request.body
        data_dict = json.loads(data)
        job_id = data_dict.get('job_id')
        action = data_dict.get('action')
        # is_admin = data_dict.get('is_admin')
        print(job_id, action)

        if not all([job_id, action]):
            return JsonResponse({"code": 400, "errmsg": "参数不全"})

        if action == 'do':
            try:
                Collection_job.objects.create(jobs_id=job_id, user_collection_id=user_id)
            except Exception as e:
                print(e)
                return JsonResponse({"code": 400, "errmsg": "收藏失败"})
            return JsonResponse({"code": 0, "errmsg": "收藏成功"})

        elif action == 'undo':
            try:
                job = Collection_job.objects.get(jobs_id=job_id, user_collection_id=user_id)
                job.delete()
            except Exception as e:
                print(e)
                return JsonResponse({"code": 400, "errmsg": "取消收藏失败"})
            return JsonResponse({"code": 0, "errmsg": "取消收藏成功"})
